#include <stdarg.h>
#include <stdio.h>
#include "securec.h"
#include "los_interrupt.h"

unsigned int intSave = 0;


//print函数的buffer大小
#define BUFSIZE  512 

static void dputs(char const *s, int (*pFputc)(int n, FILE *cookie), void *cookie)
{
    intSave = LOS_IntLock();

    while (*s) {
        pFputc(*s++, cookie);
    }

    LOS_IntRestore(intSave);
}

int printf(const char *__restrict __format, ...)
{
    char buf[BUFSIZE] = { 0 };
    int len;
    va_list ap;
    va_start(ap, __format);
    len = vsnprintf_s(buf, sizeof(buf), BUFSIZE - 1, __format, ap);
    va_end(ap);
    if(len > 0) {
        dputs(buf, fputc, 0);
    } else {
        dputs("printf error!\n", fputc, 0);
    }
    return len;
}

int sprintf(char *__restrict   __s, const char *__restrict  __format, ...)
{
    va_list args;
    int val;

    va_start(args, __format);
    val = vsprintf_s(__s,  BUFSIZE - 1,  __format,  args);
    va_end(args);

    return val;
}

#ifdef LOSCFG_LIBC_NEWLIB
int __wrap_printf(char const  *fmt, ...)
#else /* LOSCFG_LIBC_NEWLIB */
int printf(char const  *fmt, ...)
#endif /* LOSCFG_LIBC_NEWLIB */
{
#define BUFSIZE 1024  // fit the length of LOG_BUF_SIZE in hiview_log.c
    char buf[BUFSIZE] = { 0 };
    va_list ap;
    va_start(ap, fmt);
    int len = vsnprintf_s(buf, sizeof(buf), BUFSIZE - 1, fmt, ap);
    va_end(ap);
    if (len > 0) {
        dputs(buf, fputc, 0);
    } else {
        dputs("printf error!\n", fputc, 0);
    }
    return len;
}

